<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">

        <el-button type="primary" @click="showDialogTrademark"><el-icon>
            <Plus />
          </el-icon>添加</el-button>
      </div>
    </template>
    <!-- data属性表示表格的数据源，  border是让表格有竖线-->
    <!-- label当前的列的名称 -->
    <!-- prop是当前列要显示的数据 所对应的属性 -->
    <el-table v-loading="loading" :data="trademarkList" border style="width: 100%;margin-bottom: 30px;">
      <el-table-column type="index" align="center" label="序号" width="90" />
      <el-table-column prop="tmName" align="center" label="品牌名称" width="180" />
      <el-table-column prop="address" label="品牌LoGo">
        <template v-slot="{ row }">
          <div>
            <img :src="row.logoUrl" width="100">
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="操作">

        <template v-slot="{ row }">
          <el-button type="warning" :icon="Edit" size="small" @click="changeTrademark(row)"></el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="deleteTrademarkInfo(row)"></el-button>
        </template>


      </el-table-column>
    </el-table>
    <!-- 分页器 -->


    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10, 15]"
      :small="small" :disabled="disabled" :background="background" layout=" prev, pager, next, jumper,->, sizes,total,"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />


    <!-- 点击添加时，弹出对话框 -->

    <el-dialog v-model="dialogFormVisible" :title="`${form.id ? '编辑品牌':'添加品牌'}`"  >
      <el-form :model="form" ref="trademarkFormRef"  :rules="rules">
        <el-form-item label="品牌名称" :label-width="formLabelWidth"  prop="tmName">
          <el-input v-model="form.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" :label-width="formLabelWidth"  prop="logoUrl">
          <el-input v-if="form.logoUrl" v-model="form.logoUrl" autocomplete="off" style="display:none"/>
          <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/upload`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(trademarkFormRef)">
            确定
          </el-button>
        </span>
      </template>

      <template #tip>
        <div class="el-upload__tip">
          只能上传jpg/png文件，不超过2mb
        </div>
      </template>
    </el-dialog>


  </el-card>
</template>
<script lang="ts">
export default {
  name: 'Trademark'
}
</script>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { reqGetTrademarkInfoData, reqSaveTrademarkInfo, reqDelTrademarkInfo, UpDateTrademarkInfo } from '@/api/product/trademark'
// 上传图片
import { ElMessage, ElMessageBox, } from 'element-plus'

import type { UploadProps, } from 'element-plus'
// 导入类型约束文件
import type { TrademarkListModel, TrademarkModel } from "@/api/product/model/trademarkModel"
// 对于添加数据进行判断
import type { FormInstance, FormRules } from 'element-plus'


const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '品牌名称不能为空', trigger: 'blur' },
    { min: 2, max: 6, message: '长度至少在2-6位', trigger: 'blur' },
  ],
  logoUrl: [
    {
      required: true,
      message: '请添加图片ss',
      trigger: 'change',
    },
  ],})


const currentPage = ref(1)

const pageSize = ref(3)

const small = ref(false)
const background = ref(false)
const disabled = ref(false)
// 对话框的数据
const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '90px'
const total = ref(0)
const trademarkFormRef = ref<FormInstance>()
// 初始化我所要渲染的数据
const initTrademark = () => ({ tmName: '', logoUrl: '' })

// 将我初始化的数据存储到form中，
const form = reactive<TrademarkModel>(initTrademark())
// 6图片上传的数据
const imageUrl = ref('')
const BASE_URL = import.meta.env.VITE_API_URL
// 图片上传成功后触发的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  //将返回的图片的服务器连接存入
  form.logoUrl = response.data;
    //清除以前放入验证信息
    trademarkFormRef.value?.clearValidate()
}
//7 图片上传之前要验证图片的格式与大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgTypes = ['image/jpeg', 'imgage/jpg', 'imgage/gif']
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error('请添加正确格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片的大小不能超过2mb')
    return false
  }
  return true
}
// 8点击添加时弹出对话kuang
const showDialogTrademark = () => {
  // 清空上一次残留的数据
  Object.assign(form, initTrademark())

  dialogFormVisible.value = true;
  // 删除id
  delete form.id
  //清除以前放入验证信息
  trademarkFormRef.value?.clearValidate()



}

// 9：点击确定时我要请求存储我图片的数据
const btnTrademark = async () => {
  // 先判断我是添加还是修改，添加的没有id
  if (form.id) {
    // 更新所要执行的逻辑
    await UpDateTrademarkInfo(form)


  } else {
    //添加所要执行 的逻辑
    const res = await reqSaveTrademarkInfo(form)
    //当前页码要从第一页开始
    currentPage.value = 1;
  }

  //添加成功
  ElMessage.success('添加成功')
  //关闭对话kuang
  dialogFormVisible.value = false;

  //重新再渲染页面
  getTrademarkInfoData()
}
//10点击删除，删除我的当条数据
const deleteTrademarkInfo = async (row: TrademarkModel) => {
  ElMessageBox.confirm(
    `确定删除${row.tmName}码`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )

    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除了这条数据',
      })
      //重新发送请求渲染数据
      getTrademarkInfoData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败了，惊喜不，意外不',
      })
    })
  await reqDelTrademarkInfo(row.id as number)

}
//11编辑单个品牌，并在对话框中回显数据
const changeTrademark = (row: TrademarkModel) => {
  //使用object.assign来重新覆盖数据
  // console.log(11)
  Object.assign(form, row)
  // 弹出对话框
  dialogFormVisible.value = true;
    //清除以前放入验证信息
    trademarkFormRef.value?.clearValidate()

}
//12提交数据验证
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      btnTrademark();
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 5loading效果
const loading = ref(true)
// 4当前每一页显示多少条数据
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  //我的每页显示多少数据已改变，页面就要从第一页开始
  currentPage.value = 1;
  // 重新请求数据
  getTrademarkInfoData()

}
//3改变当前的页码
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  // 将当前的页码在页面中显示
  currentPage.value = val;
  // 然后重新渲染数据
  getTrademarkInfoData()
}
//定义一个数组，用户存放我响应回来的数据，要是用reatcive，的话，会丢失响应式
const trademarkList = ref<TrademarkListModel>([])
//1定义一个可以获取品牌数据的函数
const getTrademarkInfoData = async () => {
  const result = await reqGetTrademarkInfoData(currentPage.value, pageSize.value)
  // console.log(result)
  //将数据存入tradelist
  trademarkList.value = result.records;
  total.value = result.total;
  loading.value = false

}
//2组件以挂载就获取数据
onMounted(() => {
  getTrademarkInfoData()
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>